import { useState } from "react";
import { cn } from "@/lib/utils";
import Sidebar from "@/components/Sidebar";
import FileList from "@/components/FileList";
import StorageUsage from "@/components/StorageUsage";
import FileUploader from "@/components/FileUploader";
import ConnectionStatus from "@/components/ConnectionStatus";
import { FileItem } from "@/components/FileList";

const loadFilesFromStorage = (): FileItem[] => {
    const savedFiles = localStorage.getItem("cloudFiles");
    return savedFiles ? JSON.parse(savedFiles) : [];
};

const calculateStorageUsed = (files: FileItem[]): number => {
    return files.reduce((total, file) => {
        const sizeParts = file.size.split(" ");
        const size = parseFloat(sizeParts[0]);
        const unit = sizeParts[1];

        switch (unit) {
        case "KB":
            return total + size / (1024 * 1024);
        case "MB":
            return total + size / 1024;
        case "GB":
            return total + size;
        default:
            return total;
        }
    }, 0);
};

const calculateStorageByType = (files: FileItem[]): { document: number, image: number, video: number, other: number } => {
  const storageByType = {
    document: 0,
    image: 0,
    video: 0,
    other: 0
  };

  files.forEach(file => {
    const sizeParts = file.size.split(" ");
    const size = parseFloat(sizeParts[0]);
    const unit = sizeParts[1];
    
    let sizeInGB = 0;
    switch (unit) {
      case "KB":
        sizeInGB = size / (1024 * 1024);
        break;
      case "MB":
        sizeInGB = size / 1024;
        break;
      case "GB":
        sizeInGB = size;
        break;
      default:
        sizeInGB = 0;
    }

    switch (file.type) {
      case "document":
        storageByType.document += sizeInGB;
        break;
      case "image":
        storageByType.image += sizeInGB;
        break;
      case "video":
        storageByType.video += sizeInGB;
        break;
      default:
        storageByType.other += sizeInGB;
    }
  });

  return storageByType;
}

const saveFilesToStorage = (files: FileItem[]) => {
    localStorage.setItem("cloudFiles", JSON.stringify(files));
};

export default function Home() {
    const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
    const [activeView, setActiveView] = useState("files");
    const [files, setFiles] = useState<FileItem[]>(loadFilesFromStorage);
  const [storageUsed, setStorageUsed] = useState<number>(calculateStorageUsed(loadFilesFromStorage()));
  const [storageByType, setStorageByType] = useState<{ document: number, image: number, video: number, other: number }>(
    calculateStorageByType(loadFilesFromStorage())
  );
  const storageTotal = 200;

    const addFile = (newFile: File) => {
        const fileId = Date.now().toString();
        let fileType = "file";
        let fileIcon = "fa-file-o";

        if (newFile.type.startsWith("image/")) {
            fileType = "image";
            fileIcon = "fa-file-image-o";
        } else if (newFile.type.startsWith("video/")) {
            fileType = "video";
            fileIcon = "fa-file-video-o";
        } else if (newFile.type.startsWith("audio/")) {
            fileType = "audio";
            fileIcon = "fa-file-audio-o";
        } else if (newFile.type.includes("pdf")) {
            fileType = "document";
            fileIcon = "fa-file-pdf-o";
        } else if (newFile.type.includes("word")) {
            fileType = "document";
            fileIcon = "fa-file-word-o";
        } else if (newFile.type.includes("excel")) {
            fileType = "document";
            fileIcon = "fa-file-excel-o";
        } else if (newFile.type.includes("powerpoint")) {
            fileType = "document";
            fileIcon = "fa-file-powerpoint-o";
        } else if (newFile.name.endsWith(".txt")) {
            fileType = "document";
            fileIcon = "fa-file-text-o";
        }

        let fileSize: string;

        if (newFile.size < 1024) {
            fileSize = `${newFile.size} B`;
        } else if (newFile.size < 1024 * 1024) {
            fileSize = `${(newFile.size / 1024).toFixed(1)} KB`;
        } else if (newFile.size < 1024 * 1024 * 1024) {
            fileSize = `${(newFile.size / (1024 * 1024)).toFixed(1)} MB`;
        } else {
            fileSize = `${(newFile.size / (1024 * 1024 * 1024)).toFixed(1)} GB`;
        }

        const reader = new FileReader();

        reader.onload = e => {
            const fileData = e.target?.result as string;

            const fileToAdd: FileItem = {
                id: fileId,
                name: newFile.name,
                size: fileSize,
                modified: new Date().toISOString().split("T")[0],
                type: fileType,
                icon: fileIcon,
                data: fileData
            };

            const updatedFiles = [...files, fileToAdd];
            setFiles(updatedFiles);
            saveFilesToStorage(updatedFiles);
            setStorageUsed(calculateStorageUsed(updatedFiles));
            setStorageByType(calculateStorageByType(updatedFiles));
        };

        reader.readAsDataURL(newFile);
    };

    const deleteFile = (fileId: string) => {
        const updatedFiles = files.filter(file => file.id !== fileId);
        setFiles(updatedFiles);
        saveFilesToStorage(updatedFiles);
        setStorageUsed(calculateStorageUsed(updatedFiles));
    };

    return (
        <div
            className="flex h-screen bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100 overflow-hidden">
            {}
            <Sidebar
                isCollapsed={isSidebarCollapsed}
                onToggle={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
                activeView={activeView}
                onViewChange={setActiveView}
                storageUsed={storageUsed}
                storageTotal={storageTotal} />
            {}
            <div className="flex-1 flex flex-col overflow-hidden">
                {}
                <header
                    className="h-16 border-b border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-800/50 backdrop-blur-sm flex items-center justify-between px-6">
                    <div className="flex items-center gap-4">
                        <h1 className="text-xl font-semibold">
                            {activeView === "files" ? "我的文件" : activeView === "settings" ? "连接设置" : "存储概览"}
                        </h1>
                    </div>
                    <div className="flex items-center gap-4">
                        <ConnectionStatus ip="192.168.2.2" isConnected={true} />
                        <button
                            className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors">
                            <i class="fa-solid fa-user-circle text-xl"></i>
                        </button>
                    </div>
                </header>
                {}
                <main className="flex-1 overflow-y-auto p-6">
                    {activeView === "files" && <div className="space-y-6">
                        {}
                        <FileUploader onFileUpload={addFile} />
                        {}
                        <div
                            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                            <div
                                className="p-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
                                <h2 className="font-medium">最近文件</h2>
                                <div className="flex gap-2">
                                    <button className="p-2 rounded hover:bg-gray-100 dark:hover:bg-gray-700">
                                        <i class="fa-solid fa-th-large"></i>
                                    </button>
                                    <button className="p-2 rounded bg-gray-100 dark:bg-gray-700">
                                        <i class="fa-solid fa-list"></i>
                                    </button>
                                </div>
                            </div>
                            <FileList files={files} onDelete={deleteFile} />
                        </div>
                    </div>}
                    {activeView === "storage" && <div className="space-y-6">
                        <div
                            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6"
                            style={{
                                borderRadius: "0px"
                            }}>
                            <h2 className="text-xl font-semibold mb-6">存储使用情况</h2>
                             <StorageUsage 
                               used={storageUsed} 
                               total={storageTotal} 
                               fileTypes={storageByType} 
                             />
                            <p className="text-sm text-gray-500 mt-2">数据存储在浏览器本地，清除浏览器数据将导致文件丢失
                                                 </p>
                            <div className="mt-8 grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div
                                    className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg border border-blue-100 dark:border-blue-800">
                                    <h3 className="text-sm text-gray-500 dark:text-gray-400 mb-1">总存储容量</h3>
                                    <p className="text-2xl font-semibold">{storageTotal}GB</p>
                                </div>
                                <div
                                    className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg border border-green-100 dark:border-green-800">
                                    <h3 className="text-sm text-gray-500 dark:text-gray-400 mb-1">已使用</h3>
                                    <p className="text-2xl font-semibold">{storageUsed.toFixed(2)}GB</p>
                                </div>
                                <div
                                    className="bg-purple-50 dark:bg-purple-900/20 p-4 rounded-lg border border-purple-100 dark:border-purple-800">
                                    <h3 className="text-sm text-gray-500 dark:text-gray-400 mb-1">剩余空间</h3>
                                    <p className="text-2xl font-semibold">{(storageTotal - storageUsed).toFixed(2)}GB</p>
                                </div>
                            </div>
                        </div>
                        <div
                            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                            <h2 className="text-xl font-semibold mb-6">文件类型分布</h2>
                            <div className="h-64">
                                {}
                                <div className="flex items-center justify-center h-full text-gray-500">
                                    <i class="fa-solid fa-chart-pie text-5xl mb-2 block"></i>
                                    <p>文件类型分布图表</p>
                                </div>
                            </div>
                        </div>
                    </div>}
                    {activeView === "settings" && <div
                        className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <h2 className="text-xl font-semibold mb-6">设备连接设置</h2>
                        <div className="space-y-6">
                            <div>
                                <label
                                    className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">托管设备IP地址
                                                      </label>
                                <input
                                    type="text"
                                    value="192.168.2.2"
                                    className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" />
                            </div>
                            <div>
                                <label
                                    className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">连接状态
                                                      </label>
                                <div
                                    className="flex items-center gap-2 p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
                                    <span className="w-3 h-3 rounded-full bg-green-500"></span>
                                    <span>已连接到 192.168.2.2</span>
                                </div>
                            </div>
                            <div>
                                <label
                                    className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">数据传输加密
                                                      </label>
                                <div className="flex items-center">
                                    <input type="checkbox" id="encryption" checked className="mr-2" />
                                    <label htmlFor="encryption">启用传输加密</label>
                                </div>
                            </div>
                            <div className="pt-4 border-t border-gray-200 dark:border-gray-700">
                                <button
                                    className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">保存设置
                                                      </button>
                            </div>
                        </div>
                    </div>}
                </main>
            </div>
        </div>
    );
}